package com.sxt.util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * @Description:Jdbc连接工具类
 * @author: Mr.T
 * @date 2020-10-23 17:27
 */
public  class JdbcUtil {
    /**
     * 驱动
     */
    private static final String DRIVER;
    /**
     * 连接地址
     */
    private static final String URL;
    /**
     * 登录名
     */
    private static final String USERNAME;
    /**
     * 密码
     */
    private static final String PASSWORD;

    static {
        //查找到JDBC的配置文件
        InputStream in = JdbcUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
        if (in == null){
            System.err.println("配置文件没有找到");
        }
        //创建属性文件对象  用来接收配置文件信息
        Properties prop = new Properties();
        try {
            prop.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //获取属性信息
        DRIVER = prop.getProperty("jdbc.driver");
        URL = prop.getProperty("jdbc.url");
        USERNAME = prop.getProperty("jdbc.username");
        PASSWORD = prop.getProperty("jdbc.password");
        //加载驱动
        try {
//            com.jdbc.mysql.Driver
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取连接方法
     * @return
     */
    public static Connection getConn(){
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return  connection;
    }

    /**
     * 释放资源 用于更新
     * @param conn 连接对象
     * @param state 指令操作对象
     */
    public static void close(Connection conn, Statement state){
        if (state!=null){
            try {
                state.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

        if (conn != null){
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    /**
     * 释放资源   用于查询
     * @param conn
     * @param state
     * @param rs
     */
    public static void close(Connection conn, Statement state, ResultSet rs){
        if (rs != null){
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        close(conn,state);
    }


    public static void main(String[] args) {
        System.out.println(getConn());
    }


}
